package com.linghang.lhonline.controller;


import com.linghang.lhonline.constant.CookieConstant;
import com.linghang.lhonline.constant.RedisConstant;
import com.linghang.lhonline.Util.CookieUtil;
import com.linghang.lhonline.Util.ImageUtil;
import com.linghang.lhonline.Util.ResultVOUtil;
import com.linghang.lhonline.VO.ResultVO;
import com.linghang.lhonline.VO.UsersVO;
import com.linghang.lhonline.dataobject.GroupType;
import com.linghang.lhonline.dataobject.Users;
import com.linghang.lhonline.enums.PositionEnums;
import com.linghang.lhonline.service.GroupTypeService;
import com.linghang.lhonline.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UsersController {

    private UsersService usersService;
    private GroupTypeService groupTypeService;
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public UsersController(UsersService usersService, GroupTypeService groupTypeService, StringRedisTemplate stringRedisTemplate) {
        this.usersService = usersService;
        this.groupTypeService = groupTypeService;
        this.stringRedisTemplate = stringRedisTemplate;

    }

    @PostMapping("/image")
    public ResultVO image(@RequestParam("student_id") String studentId,
                          @RequestParam("user_image") MultipartFile multipartFile) {

        Users users = usersService.findByStudentId(studentId);

        File file = ImageUtil.upload(multipartFile);

        if (users == null) {
            return ResultVOUtil.error("查无此人");
        }

        if (file == null) {
            return ResultVOUtil.error("没有选择图像文件");
        }

        users.setImageUrl("https://152.136.102.20/" + file.getName());

        usersService.save(users);
        return ResultVOUtil.success("上传成功");

    }

    @PostMapping("/login")
    public ResultVO login(@RequestParam("student_id") String studentId,
                          HttpServletResponse response,
                          @RequestParam("password") String password) {

        //1、匹配数据
        Users users = usersService.findByStudentId(studentId);
        if (users == null) {
            return ResultVOUtil.error("用户不存在");
        }
        if (!password.equals(users.getPassword())) {
            return ResultVOUtil.error("密码有误");
        }

        //2、设置token -> redis
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConstant.EXPIRE;
        stringRedisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token), studentId, expire, TimeUnit.SECONDS);

        //3、设置token -> cookie
        CookieUtil.set(response, CookieConstant.TOKEN, token, expire);

        if (password.equals("123456")) {
            return ResultVOUtil.warning("登录成功，但密码为初始密码，应立即修改",users.getPosition());
        }

        return ResultVOUtil.success("用户登录",users.getPosition());
    }

    @PostMapping("/register")
    public ResultVO register(@RequestParam("group") String groupName,
                             @RequestParam("class") String className,
                             @RequestParam("student_id") String studentId) {

        List<Users> usersList = usersService.findAll();
        for (Users users : usersList) {
            if (users.getStudentId().equals(studentId)) {
                return ResultVOUtil.error("学号已存在");
            }
        }

        Users users = new Users();

        users.setGroupName(groupName);
        users.setStudentId(studentId);
        users.setUserName(studentId);
        users.setPosition(PositionEnums.CREW.getCode());
        users.setPassword("123456");
        users.setClassName(className);

        usersService.save(users);

        return ResultVOUtil.success("注册成功");
    }

    @PostMapping("/modify_by_student")
    public ResultVO modifyByStudent(@RequestParam("student_id") String studentId,
                                    @RequestParam("user_name") String userName,
                                    @RequestParam("password") String password) {

        Users users = usersService.findByStudentId(studentId);

        if (users == null) {
            return ResultVOUtil.error("没有此用户");
        }

        users.setPassword(password);
        users.setUserName(userName);

        usersService.save(users);
        return ResultVOUtil.success("修改成功");
    }


    @PostMapping("/modify_by_leader")
    public ResultVO modifyByLeader(@RequestParam("group") String groupName,
                                   @RequestParam("student_id") String studentId,
                                   @RequestParam("class") String className,
                                   @RequestParam("position") Integer position) {

        Users users = usersService.findByStudentId(studentId);

        if (users == null) {
            return ResultVOUtil.error("没有此用户");
        }

        users.setGroupName(groupName);
        users.setPosition(position);
        users.setClassName(className);

        usersService.save(users);

        return ResultVOUtil.success("修改成功");
    }

    @PostMapping("/delete_crew")
    public ResultVO delete(@RequestParam("leader_id") String leaderId,
                           @RequestParam("student_id") String studentId) {

        Users leader = usersService.findByStudentId(leaderId);
        if (leader == null) {
            return ResultVOUtil.error("组长学号有误");
        }

        if (leader.getPosition() == 0) {
            return ResultVOUtil.error("该成员无权限");
        }

        Users student = usersService.findByStudentId(studentId);
        if (student == null) {
            return ResultVOUtil.error("组员学号有误");
        }

        if (student.getGroupName().equals(leader.getGroupName())) {
            usersService.delete(studentId);
            return ResultVOUtil.success("注销成功");
        } else {
            return ResultVOUtil.error("该组长与组员不是同一组，无法删除");
        }
    }

    @GetMapping("user_list")
    public ResultVO userList(@RequestParam("group") String groupName) {

        List<Users> users = usersService.findByGroupName(groupName);

        List<Users> usersList = new ArrayList<>();
        for (Users users1 : users) {
            if (users1.getPosition() == 1) {
                usersList.add(users1);
            }
        }

        for (Users users2 : users) {
            if (users2.getPosition() == 2) {
                usersList.add(users2);
            }
        }

        for (Users users0 : users) {
            if (users0.getPosition() == 0) {
                usersList.add(users0);
            }
        }

        List<UsersVO> usersVOS = new ArrayList<>();
        for (Users users3 : usersList) {
            UsersVO usersVO = new UsersVO();
            BeanUtils.copyProperties(users3, usersVO);

            usersVOS.add(usersVO);
        }

        return ResultVOUtil.success("获取该组全部成员", usersVOS);
    }

    @PostMapping("re_password")
    public ResultVO rePassword(@RequestParam("student_id") String studentId) {

        Users users = usersService.findByStudentId(studentId);

        if (users == null) {
            return ResultVOUtil.error("组员学号有误");
        }

        users.setPassword("123456");
        usersService.save(users);

        return ResultVOUtil.success("重置成功");
    }

    @GetMapping("group_list")
    public ResultVO groupList() {

        List<String> list = groupTypeService.groupList();

        return ResultVOUtil.success("获取所有组别", list);
    }

    @PostMapping("/new_group")
    public ResultVO newGroup(@RequestParam("group") String groupName) {

        List<String> groupList = groupTypeService.groupList();

        for (String name : groupList) {
            if (name.equals(groupName)) {
                return ResultVOUtil.error("此组名已存在，请更换");
            }
        }

        GroupType groupType = new GroupType();

        groupType.setGroupName(groupName);
        groupTypeService.save(groupType);

        return ResultVOUtil.success("新建成功");
    }

    @PostMapping("/delete_group")
    public ResultVO deleteGroup(@RequestParam("group") String groupName) {

        GroupType group = groupTypeService.findByGroupName(groupName);


        List<Users> usersList = usersService.findByGroupName(group.getGroupName());

        if (usersList.size() != 0) {
            return ResultVOUtil.error("该组内仍有成员，无法删除");
        } else {
            groupTypeService.delete(group);
            return ResultVOUtil.success("删除成功");
        }
    }
}
